package pers.dawnyang.common.util.security;

import java.util.List;
import org.apache.commons.lang3.StringUtils;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import pers.dawnyang.common.annotation.Secret;

/**
 * 传输参数加密解密工具
 * 
 * @author dawn yang 2021年5月12日 下午8:26:53
 */

public class SecurityUtil {

  //private static String aseKey = "123456789qwertyu";
  private static String aseKey = "1234123412ABCDEF";


  public static <T> List<T> decList(List<T> list) {
    for (T t : list) {
      dec(t);
    }
    return list;
  }

  public static <T> T dec(T obj) {
    String encodeHexStr = HexUtil.encodeHexStr(aseKey);
    byte[] decodeHex = HexUtil.decodeHex(encodeHexStr);
    AES aes = SecureUtil.aes(decodeHex);
    if (null != obj) {
      Class<? extends Object> class1 = obj.getClass();
      if(class1.isAnnotationPresent(Secret.class)) {
        if(null!= obj && StringUtils.isNotBlank(obj.toString())) {
          System.out.println(obj.toString());
          aes.decryptStr(obj.toString());
        }
        
        /*
         * Field[] fields = class1.getDeclaredFields(); for (Field field : fields) {
         * field.setAccessible(true); try { Object object = field.get(obj); if (null != object &&
         * StringUtils.isNoneBlank(object.toString())) { String decryptStr =
         * aes.decryptStr(object.toString()); field.set(obj, decryptStr); } } catch (Exception e) {
         * e.printStackTrace(); } }
         */
      }
    }
    return obj;
  }


  public static void main(String[] args) {
    String content = "test中文";
    // 随机生成密钥
//    SecretKey generateKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue());
//    byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
//    System.out.println(key);
//    System.out.println(key.toString());
//    System.out.println(HexUtil.encodeHexStr(key));
    // 构建
    //byte[] bytes = aseKey.getBytes();
    
    String encodeHexStr = HexUtil.encodeHexStr(aseKey);
    byte[] decodeHex = HexUtil.decodeHex(encodeHexStr);
    AES aes = SecureUtil.aes(decodeHex);

    
    // 加密
    byte[] encrypt = aes.encrypt(content);
    System.out.println(encrypt);
    // 解密
    byte[] decrypt = aes.decrypt(encrypt);
    System.out.println(decrypt);

    // 加密为16进制表示
    String encryptHex = aes.encryptHex(content);
    System.out.println(encryptHex);
    // 解密为原字符串
    String decryptStr = aes.decryptStr(encryptHex);
    System.out.println(decryptStr);

  }


}
